from django.shortcuts import render
from utils.customerutils import CustomerUtils
from utils.responsestatus import ResponseStatus
from utils import responsedata
from django.core.paginator import Paginator
from .models import Department
from django.db import IntegrityError
from django.db.models.deletion import ProtectedError


# Create your views here.
# 部门分页
def dept_page(request):
    if request.method == 'POST':
        form_data = CustomerUtils.get_request_data(request)
        dept_list = Department.objects.all().order_by('-id')
        paginator = Paginator(dept_list, form_data.get('size', 5))
        total = paginator.count
        # 当前页数据
        current_page = paginator.page(form_data.get('page', 1))
        table_data = list(current_page.object_list.values())
        response = {
            'code': ResponseStatus.BUSINESS_SUCCESS,
            'data': {
                'total': total,
                'tableData': table_data
            }
        }
        return CustomerUtils.response_json(response)


def dept_one(request, id):
    dept = Department.objects.filter(id=id).first()
    response = {
        'code': ResponseStatus.BUSINESS_SUCCESS,
        'data': {
            'dept': dept
        }
    }
    return CustomerUtils.response_json(response)


def dept_list(request):
    dept_list = Department.objects.all()
    depts = []
    for dept in dept_list:
        depts.append({
            'id': dept.id,
            'dept_name': dept.dept_name
        })
    resp = {
        'code': ResponseStatus.BUSINESS_SUCCESS,
        'data': {
            'depts': depts
        }
    }
    return CustomerUtils.response_json(resp)


def dept_insert_edit(request):
    if request.method == 'POST':
        form_data = CustomerUtils.get_request_data(request)
        print(form_data)
        id = form_data.get('id')
        try:
            if id is None:
                Department(**form_data).save()
                return CustomerUtils.response_json(responsedata.BUSINESS_SUCCESS_DATA)
            Department.objects.filter(id=id).update(**form_data)
            return CustomerUtils.response_json(responsedata.BUSINESS_SUCCESS_DATA)
        except IntegrityError as e:
            result = responsedata.BUSINESS_ERROR_DATA
            result['message'] = str(e)
            return CustomerUtils.response_json(result)


def dept_batch_remove(request):
    if request.method == 'POST':
        # {'ids':[]}
        form_data = CustomerUtils.get_request_data(request)
        # 获取所有需要删除的角色id
        ids = form_data.get('ids')
        # delete from role where id in(1,2,3)
        try:
            Department.objects.filter(id__in=ids).delete()
            return CustomerUtils.response_json(responsedata.BUSINESS_SUCCESS_DATA)
        except ProtectedError as e:
            response = responsedata.BUSINESS_ERROR_DATA
            response['message'] = '部门被占用不能删除!!!'
            return CustomerUtils.response_json(response)
